import 'package:flutter/material.dart';

class MyRebuildWidget extends StatefulWidget {
  final String text;

  const MyRebuildWidget({super.key, required this.text});

  @override
  _MyRebuildWidgetState createState() => _MyRebuildWidgetState();
}

class _MyRebuildWidgetState extends State<MyRebuildWidget> {
  @override
  void initState() {
    // TODO: implement initState
    print('JtTag:initState');
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    print('JtTag:dispose');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print("build 执行: ${widget.text}");
    return Text(widget.text);
  }
}

class Test_V_U_key extends StatefulWidget {
  const Test_V_U_key({super.key});

  @override
  State<Test_V_U_key> createState() => _Test_V_U_key();
}

class _Test_V_U_key extends State<Test_V_U_key> {
  final valueNotifier1 = ValueNotifier(0);
  final valueNotifier2 = ValueNotifier(0);
  final key = ValueKey("固定");

  @override
  Widget build(BuildContext context) {
    print('JtTag:_Test_V_U_key:build');
    return Scaffold(
        appBar: AppBar(title: const Text('MyRebuildWidget')),
        body: Column(children: [
          ValueListenableBuilder<int>(
            valueListenable: valueNotifier1,
            builder: (context, value, child) {
              return Column(
                children: [
                  MyRebuildWidget(key: key, text: "只有 key 改变才会重建"),
                ],
              );
            },
          ),
          TextButton(
              onPressed: () {
                valueNotifier1.value++;
              },
              child: Text('重建1')),
          ValueListenableBuilder<int>(
            valueListenable: valueNotifier2,
            builder: (context, value, child) {
              return Column(
                children: [
                  MyRebuildWidget(key: UniqueKey(), text: "不会缓存，每次都新建"),
                ],
              );
            },
          ),
          TextButton(
              onPressed: () {
                // setState(() {
                //   key2 = UniqueKey();
                // });
                valueNotifier2.value++;
              },
              child: Text('重建2')),
        ]));
  }
}
